# This file is part of Gehyra.
#
# Gehyra is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gehyra is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gehyra.  If not, see <http://www.gnu.org/licenses/>.

""" @package gehyra.bootstrap.modules.pull_gdata
Bootstrap Google Apps record reader.
Reads a Google Apps spreadsheet for the bootstrap data
$Id: pull_gdata.py 450 2011-01-20 14:28:47Z andyhhp@gmail.com $
"""

""" @file pull_gdata.py
Bootstrap Google Apps record reader.
Reads a Google Apps spreadsheet for the bootstrap data
"""


from gehyra.common.interfaces import IBootstrapPuller
from gehyra.common.logger import LOG

from twisted.web.client import getPage
from zope.interface import implements

import xml.dom.minidom


## @brief URL template for google spreadsheets feeds    
PAGE_TEMPLATE = ("https://spreadsheets.google.com/feeds/cells/"\
                 "%s/1/public/basic?max-col=1&max-row=25")

class pull_gdata(object):
    """Bootstrap Google Apps record reader.
    Reads a Google Apps spreadsheet for the bootstrap data
    """
    implements(IBootstrapPuller)

    ## @brief Tell our py2exe script to let XML be included.
    needs_xml = True
    ## @brief Tell our py2exe script to let SSL be included.
    needs_ssl = True


    def __init__(self, name, **args):
        """Constructor.
        @param name Name of this bootstrap object given in the configuration.
        @param **args Dictionary of arguments
         - sheet_key - the google spreadsheet key
        """

        ## @brief Name of this bootstrap object
        self.name = name

        if 'sheet_key' in args:
            ## @brief Google spreadsheet key
            self.key = args['sheet_key']
            del args['sheet_key']
        else:
            self.key = None
            LOG.warn("Gdata Puller '%s' has no sheet_key" % name)

        for a in args:
            LOG.warn("Gdata Puller '%s' has received "
                     "unrecognised parameter '%s'" % (name, a) )

        ## @brief twisted.internet.defer object returning the parsed information
        self.collect_d = None

    def initialize(self):
        """Initialize object.
        Nothing to do"""
        return True


    def collect(self):
        """Attempt to collect the bootstrap information.
        Read the XML feed and parse the infomation
        @return Deferred object
        """
        d = getPage(PAGE_TEMPLATE % self.key, timeout=10)

        def success(result):
            """defered success"""
            data = {}
            doc = xml.dom.minidom.parseString(result)
            for c in doc.getElementsByTagName("content"):
                if c.firstChild:
                    (k, v) = str(c.firstChild.nodeValue).split('=', 1)
                    data[k] = v
            return data

        d.addCallback(success)
        return d

    def desc(self):
        """Short description.
        @return String giving a short description for the logs.
        """
        if self.key is not None:
            return "Gdata Puller '%s' reading '%s'" % (self.name, self.key)
        else:
            return "Gdata Puller '%s' with no hostname" % self.name
